package com.sec.etech.presale.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sec.etech.common.dao.SerialCode;
import com.sec.etech.common.dao.SubSerialCode;
import com.sec.etech.common.fanutil.FanUtil;
import com.sec.etech.common.service.SerialCodeService;
import com.sec.etech.presale.dao.CRM_PreProjectDao;
import com.sec.etech.presale.model.CRM_PreProject;
import com.sec.etech.sys.msg.EtechMailService;
import com.sec.etech.sys.msg.model.EtechEmailMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * @version : 1.0
 * @auther : 老邓
 * @date : 2020/11/3 12:57
 * @description:
 */
@Service
public class CRM_PreProjectService {

    @Autowired
    private EtechMailService mailService;
    @Autowired
    private SerialCodeService serialCodeService;
    @Autowired
    private CRM_PreProjectDao crm_preProjectDao;
    @Resource
    private PrePorjectService prePorjectService;

    //CRM对接操作
    public String set(String action, String datas) {
        try {
            //数据初始化
            CRM_PreProject crm_preProject = new CRM_PreProject();
            crm_preProject = parsing(datas);
            //开始执行
            if (action.equals("add")) {
                if (!crm_preProjectDao.getNpdfs1Id(crm_preProject.getCrm_opportunity_id()).equals("0")) {
                    throw new Exception("给定的crm_opportunity_id已存在，无法重复添加！");
                }
                if (crm_preProject.getCrm_parentid().equals("0")) {
                    //新建主项目
                    return add(crm_preProject);
                } else {
                    //新建子项目
                    String parentid = crm_preProjectDao.getNpdfs1Id(crm_preProject.getCrm_parentid());
                    if (parentid.equals("0")) throw new Exception("给定的parentid无法找到对应的S1ID，无法执行添加子项操作！");
                    return sub(crm_preProject, parentid);
                }
            } else if (action.equals("edt")) {
                crm_preProject.setNpdfs1id(crm_preProjectDao.getNpdfs1Id(crm_preProject.getCrm_opportunity_id()));
                if (crm_preProject.getNpdfs1id().equals("0")) {
                    throw new Exception("给定的crm_opportunity_id无法找到对应的S1ID或者该S1条目已取消！");
                }
                return edt(crm_preProject);
            } else return "";//其他非法操作
        } catch (Exception e) {
            FanUtil.catchAndMail("1307","CRM 数据对接失败",e);
            sendErrorInfoEmail("CRM数据对接失败，失败原因：" + e.getMessage() + "<br>" +
                    "操作动作：" + action + "<br>" +
                    "数据：" + datas);
            return "";
        }
    }

    //CRM数据解析
    public CRM_PreProject parsing(String datas) {
        JSONObject crmData = JSON.parseObject(datas);
        CRM_PreProject crm_preProject = new CRM_PreProject();
        crm_preProject.setProjectname(crmData.getString("projectname").trim());
        crm_preProject.setReformid(crm_preProjectDao.getDataId(crmData.getString("reform").trim(), "reform"));
        crm_preProject.setSchemeid(crm_preProjectDao.getDataId(crmData.getString("scheme").trim(), "scheme"));
        crm_preProject.setOriginid(crm_preProjectDao.getDataId(crmData.getString("origin").trim(), "origin"));
        crm_preProject.setOrderdprtid(crm_preProjectDao.getDataId(crmData.getString("orderdprt").trim(), "orderdprt"));
        crm_preProject.setDutyid(crm_preProjectDao.getDataId(crmData.getString("duty").trim(), "duty"));
        crm_preProject.setCustomergroupid(crm_preProjectDao.getDataId(getCustomergroupname(crmData.getString("customergroup0").trim()).get("customergroupname"),
                "customergroup", getCustomergroupname(crmData.getString("customergroup0").trim()).get("customergroupfullname")));
        crm_preProject.setPlants(crmData.getString("plants").trim());
        crm_preProject.setInstituteid(crm_preProjectDao.getDataId(crmData.getString("institute").trim(), "institute"));
        crm_preProject.setThermalperformid(crm_preProjectDao.getDataId(crmData.getString("thermalperform").trim(), "thermalperform"));
        crm_preProject.setSalesmanageruname(crmData.getString("salesmanageruname").trim());
        crm_preProject.setQuantity(Integer.valueOf(crmData.getString("quantity")));
        crm_preProject.setPlateid(crm_preProjectDao.getDataId(crmData.getString("plate").trim(), "plate", crmData.getString("fieldname").trim()));
        crm_preProject.setDriveobjectid(crm_preProjectDao.getDataId(crmData.getString("driveobject").trim(), "driveobject"));
        crm_preProject.setSupplyscopeid(crm_preProjectDao.getDataId(crmData.getString("supplyscope").trim(), "supplyscope"));
        crm_preProject.setCountry(crmData.getString("country").trim());
        crm_preProject.setProvinceid(crm_preProjectDao.getDataId(crmData.getString("province").trim(), "province"));
        crm_preProject.setMarketid(crm_preProjectDao.getDataId(crmData.getString("market").trim(), "market"));
        crm_preProject.setProjectremark(crmData.getString("projectremark").trim().replace("'", "''"));
        crm_preProject.setActive(crmData.getString("active").trim());
        crm_preProject.setCrm_opportunity_id(crmData.getString("crm_opportunity_id").trim());
        crm_preProject.setCrm_parentid(crmData.getString("parentid").trim());
        crm_preProject.setCustomergroups(crmData.getString("customergroups").trim());
        crm_preProject.setCapacity(crmData.containsKey("capacity") ? crmData.getString("capacity") : null);
        return crm_preProject;
    }

    //解析业主集团的全称和简称
    public Map<String, String> getCustomergroupname(String customergroup) {
        String customergroupname = "", customergroupfullname = "";
        if (StrUtil.isNotBlank(customergroup) && customergroup.contains("(") && customergroup.contains(")")) {
            customergroupname = customergroup.substring(0, customergroup.indexOf("("));
            customergroupfullname = customergroup.substring(customergroup.indexOf("(") + 1, customergroup.length() - 1);
        }
        Map<String, String> data = new HashMap<>();
        data.put("customergroupname", customergroupname);
        data.put("customergroupfullname", customergroupfullname);
        return data;
    }

    //发送错误提示邮件
    public void sendErrorInfoEmail(String errorInfo) {
        EtechEmailMessage msg = new EtechEmailMessage();
        msg.setTo("381,1307");
        msg.setSubject("CRM数据对接错误提示");
        msg.setHtmlContent(errorInfo);
        mailService.sendMail(msg);
    }

    //添加操作
    public String add(CRM_PreProject crm_preProject) {
        SerialCode serialCode = new SerialCode();
        if(String.valueOf(LocalDate.now().getYear()).equals("2020")) {
            serialCode.setScope("NPDFS1_");
            serialCode.setCodeKey("num");
            serialCode.setDtName("pre_project_basicinfo");
            serialCode.setCodeNum(4);
        } else {
            serialCode.setScope("S1_");
            serialCode.setCodeKey("num");
            serialCode.setDtName("pre_project_basicinfo");
            serialCode.setMarking(crm_preProjectDao.getOrderdprtmarking(crm_preProject.getOrderdprtid()));
            serialCode.setCodeNum(3);
        }
        crm_preProject.setNum(serialCodeService.getSerialCode(serialCode));
        String npdfs1id = crm_preProjectDao.add(crm_preProject);
        if (!npdfs1id.equals("0")) {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("npdfs1id",npdfs1id);
                jsonObject.put("num",crm_preProject.getNum());
                jsonObject.put("projectname",crm_preProject.getProjectname());
                jsonObject.put("postuid","417137619324108800");
                prePorjectService.sendAddemail(jsonObject);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if (!npdfs1id.equals("0")) {
            crm_preProjectDao.setCustomergroups(npdfs1id, crm_preProject.getCustomergroups());
            return crm_preProject.getNum();
        } else return "";
    }

    //添加子项操作
    public String sub(CRM_PreProject crm_preProject, String parentid) throws Exception {
        SubSerialCode subSerialCode = new SubSerialCode();
        subSerialCode.setMainid(parentid);
        subSerialCode.setIdKey("npdfs1id");
        subSerialCode.setCodeKey("num");
        subSerialCode.setDtName("pre_project_basicinfo");
        subSerialCode.setLinkCode("_");
        subSerialCode.setSubCodeNum(2);
        crm_preProject.setNum(serialCodeService.getSubSerialCode(subSerialCode));
        prePorjectService.addSubProject(parentid);
        crm_preProject.setNpdfs1id(crm_preProjectDao.getNpdfs1IdByNum(crm_preProject.getNum()));
        if (crm_preProject.getNpdfs1id().equals("0")) throw new Exception("添加子项目时发生错误！");
        else return edt(crm_preProject);
    }

    //编辑操作
    public String edt(CRM_PreProject crm_preProject) {
        if (crm_preProject.getActive().equals("0")) crm_preProjectDao.abandon(crm_preProject.getNpdfs1id());
        else {
            crm_preProjectDao.edt(crm_preProject);
            crm_preProjectDao.setCustomergroups(crm_preProject.getNpdfs1id(), crm_preProject.getCustomergroups());
        }
        return crm_preProjectDao.getS1ByNpdfs1id(crm_preProject.getNpdfs1id()).getNum();
    }
}

